package monitor

import (
	"context"
	"fmt"
	"github.com/opentracing/opentracing-go"
	"strings"
	"time"

	"git.bybit.com/cht/asset/asset-common/pkg/metrics"
)

const (
	SUCCESS   = "SUCCESS"
	FAILED    = "FAILED"
	END       = "END"
	SUBSYSTEM = "kyc_admin_service"
	SUBFUNC   = "FUNC"
)

var (
	kycDuration = metrics.NewMethodHistogramVec(SUBSYSTEM, "duration") // 耗时统计
	kycCount    = metrics.NewCounterVec(SUBSYSTEM, "counter")          // 次数统计（单调增加）
)

func DefaultMetrics(start time.Time, span opentracing.Span, err error, lvs ...string) {
	method := strings.Join(lvs, "_")
	status := FAILED
	if err == nil {
		status = SUCCESS
	}
	kycCount.NewLabel(method, status).Inc()
	kycDuration.NewLabel(method).Observe(time.Since(start).Seconds())
	TraceFinish(span)
}

type MetricsHandler struct {
	method    string
	startTime time.Time
	lastTime  time.Time
	source    string // todo 调用来源，扩展用
}

func NewMetrics(funcName string, source string) *MetricsHandler {
	handler := &MetricsHandler{
		method:    funcName,
		startTime: time.Now(),
		lastTime:  time.Now(),
		source:    source,
	}
	handler.AddMetrics(nil, "BEGIN")
	return handler
}

func (p *MetricsHandler) AddMetrics(err error, lvs ...string) {
	method := p.method
	node := strings.Join(lvs, "_")
	if node != "" {
		method = fmt.Sprintf("%s_%s", method, node)
	}

	status := FAILED
	if err == nil {
		status = SUCCESS
	}

	kycCount.NewLabel(method, status).Inc()
	if node == END {
		kycDuration.NewLabel(method).Observe(time.Since(p.startTime).Seconds())
	} else {
		kycDuration.NewLabel(method).Observe(time.Since(p.lastTime).Seconds())
	}
	p.lastTime = time.Now() // 重复赋值当前时间，用于下一期耗时扣减
}

func DefaultTrace(ctx context.Context, lvs ...string) (opentracing.Span, context.Context) {
	tags := strings.Join(lvs, "_")
	return opentracing.StartSpanFromContext(ctx, tags)
}

func TraceFinish(span opentracing.Span) {
	if span != nil {
		span.Finish()
	}
}
